<template>
  <!-- 筛选条件集合 -->
  <div class="search-cmp-container">
    <div class="search-array-box">
      <div class="search-array-cmp">
        <el-select v-model="searchCmpValue" placeholder="请选择" style="width: 115px;margin-right: 1px;">
          <el-option 
            v-for="(item, index) in searchCmpArray" 
            :key="index"
            :label="item.label" 
            :value="item.key" 
          />
        </el-select>
        <!-- 搜索组件（输入框、下拉框、日期等） -->
        <div class="seach-type-cmp">
          <!-- 关键词 -->
          <div class="keywords-search" v-if="curSearchType === 'keywords'">
            <el-input v-model="searchForm[searchCmpValue]" placeholder="输入内容标题或正文关键词" @keyup.enter="onSubmit" clearable/>
          </div>
          <!-- 发布日期 -->
          <div class="time-search content-search-box" v-else-if="curSearchType === 'datetime'">
            <el-date-picker
                clearable
                v-model="searchForm[searchCmpValue]"
                type="daterange"
                range-separator="至"
                start-placeholder="编辑日期"
                end-placeholder="编辑日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :unlink-panels="true"
            />
          </div>
          <!-- 图片张数 -->
          <div v-else-if="curSearchType === 'count'" class="count-range content-search-box">
            <el-input-number
                v-model="searchForm[searchCmpValue][0]"
                class="mx-4"
                :min="0"
                :max="searchForm[searchCmpValue][1]"
                controls-position="right"
                :controls="false"
                clearable
            />
            <span>&nbsp;-&nbsp;</span>
            <el-input-number
                v-model="searchForm[searchCmpValue][1]"
                class="mx-4"
                :min="searchForm[searchCmpValue][0]"
                controls-position="right"
                :controls="false"
                clearable
            />
          </div>
          <!-- 单选和多选 -->
          <div v-else-if="curSearchType === 'select' || curSearchType === 'multiple'" class="content-search-box" style="width:100%;">
            <el-select
                v-model="searchForm[searchCmpValue]"
                clearable
                placeholder="请选择"
                style="width: 320px"
                :multiple="curSearchType === 'multiple' ? true : false"
                collapse-tags
                collapse-tags-tooltip
            >
              <el-option
                  v-for="option in curOptions[searchCmpValue]"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              >
                <span v-if="option.num">{{`${option.label}（${option.num}）`}}</span>
                <span v-else>{{`${option.label}`}}</span>
              </el-option>
            </el-select>
          </div>
          <div v-else-if="curSearchType === 'switch'" class="content-search-box">
            <el-switch v-model="searchForm[searchCmpValue]" inline-prompt active-text="有" inactive-text="无"/>
          </div>
          <div class="content-search-box" v-else>
            <el-input v-model="searchForm[searchCmpValue]" placeholder="请输入关键词" @keyup.enter="onSubmit" clearable/>
          </div>
        </div>
      </div>
      <div class="btns">
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </div>
    </div>
    <div class="search-tags">
      <el-tag v-for="tag in searchTagsList" :key="tag.key" @close="handleClearTag(tag)" closable effect="plain" type="info">
        <div class="label">{{`${tag.label}：`}}</div>
        <div class="value" v-if="['select','multiple'].indexOf(tag.type) != -1 " :title="tag.value">{{toShowLabel(tag)}}</div>
        <div class="value" v-else :title="tag.value">{{`${tag.value}`}}</div>
      </el-tag>
      <!-- <el-tag  @close="handleClearTag(tag)" effect="plain" type="info" > -->
        <el-button class="reset-btn" v-if="searchTagsList?.length > 0" type="primary" @click="reset" link>清空筛选条件</el-button>
      <!-- </el-tag> -->

    </div>
  </div>
</template>
<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  // searchCmpValue数组对象参数示例[{
  //   lable: '作者',
  //   key: 'author',
  //   form_type: 'author',
  //   options:[] //下拉框时使用
  // }]
  searchCmpArray: {
    type: Array,
    default: () => { 
      return [] 
    }
  }, 
  searchForm: {
    type: Object,
    default: () => { 
      return {}
    }
  }, 
  keyId: {
    type: [String, Number],
    default: ''
  }, 
})

const searchCmpValue = ref(props.searchCmpArray[0].key)
const searchCmpArray = computed(()=>{return props.searchCmpArray})
const searchForm = computed(()=>{return props.searchForm})
const curOptions = computed(()=>{
  let option = {}
  searchCmpArray.value.forEach(item => {
    if(item.options){
      option = {
        ...option,
        [item.key]: item.options
      }
    }
  })
  return option
})
// 获取当前筛选条件组件
const curSearchType = computed(() => {
  let obj = searchCmpArray.value.find(item => item.key === searchCmpValue.value)
  return obj ? obj.form_type : obj.key
}) 


// 反显单选多选label
const toShowLabel = (tag) => {
  console.log('curOptions.value',curOptions.value);
  if(Array.isArray(tag.value)){ //多选
    let arr = []
    tag.value.forEach(item => {
      let obj = curOptions.value[tag.key].find(ele => ele.value == item)
      arr.push(obj?.label || '错误')
    })
    return arr.join(', ')
  }else{ //单选
    return curOptions.value[tag.key].find(item => item.value == tag.value)?.label || '错误'
  }
}

// 清除指定条件tag
const handleClearTag = (val) => {
  if (typeof(val['key']) === 'boolean') {
    searchForm.value[val['key']] = false
  }else if (typeof(val['key']) === 'string') {
    searchForm.value[val['key']] = ''
  }else if (typeof(val['key']) === 'object') {
    searchForm.value[val['key']] = ''
  }else{
    searchForm.value[val['key']] = null
  }
  onSubmit()
}

// 重置清空检索表单的函数
const clearForm = (obj) => {
  for (let key in obj ) {
    let objExit = searchCmpArray.value.find(ele => ele.key == key)
    if(objExit){
      if (Object.prototype.toString.call(obj[key]) === '[object Boolean]') {
          obj[key] = false
      }else if (Object.prototype.toString.call(obj[key]) === '[object String]') {
          obj[key] = ''
      }else if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
          obj[key] = null
      }else if (Object.prototype.toString.call(obj[key]) === '[object Array]') {
          obj[key] = []
      }else {
          obj[key] = null
      }
    }
  }
}
// 清空
const reset = () => {
  clearForm(searchForm.value)
  onSubmit()
}
const showTags = () => {
  // 显示所有的筛选条件tags
  searchTagsList.value = []
  for (const key in searchForm.value) {
    const item = searchForm.value[key]
    if(item != undefined && item != ''){
      let obj = searchCmpArray.value.find(ele => ele.key == key)
      if(obj){
        searchTagsList.value.push({
          key,
          type: obj?.form_type,
          label: obj?.label || '-',
          value: item
        })
      }
    }
  } 
  console.log('searchTagsList.value',searchTagsList.value);
}
const emits = defineEmits(['onSubmit'])
// 搜索
const searchTagsList = ref([])
const onSubmit = () => {
  showTags()
  emits('onSubmit')
}

watch(props, () => {
  console.log('props',props);
},{deep:true})
watch(searchForm, () => {
  console.log('searchForm.value',searchForm.value);
},{deep:true})
watch(props.searchForm, () => {
  console.log('props.searchForm',props.searchForm);
},{deep:true})
watch(()=>props.keyId, (newVal, oldVal) => {
  console.log('newVal',newVal);
  console.log('oldVal',oldVal);
  if(props.keyId){
    console.log('重置keyId',searchForm.value);
    reset()
  }
})
defineExpose({
  clearForm,
  showTags
})
</script>
<style scoped lang='scss'>
.search-cmp-container{
  .search-array-box{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .btns{
      margin-left: 10px;
    }
    .search-array-cmp{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .keywords-search{
        width: 760px;
      }
      .content-search-box{
        width: 320px;
      }
      .time-search{
        ::v-deep(.el-date-editor.el-input__wrapper){
          width: 320px;
          box-sizing: border-box;
        }
      }
      ::v-deep(.ruifox-depart){
        .depart-select{
          min-height: initial;
        }
        .depart-container{
          min-height: initial;
          .chose-depart{
            margin: 0 10px;
          }
        }
      }
    }
  }
  .search-tags{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    ::v-deep(.el-tag){
      width: fit-content;
      margin-right: 10px;
      margin-top: 10px;
      .el-tag__content{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
      }
      .label{
        // color: #999;
      }
      .value{
        color: #333;
        display: inline-block;
        width: fit-content;
        max-width: 500px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .reset-btn{
      margin-top: 10px;
    }
  }
  ::v-deep(.el-form-item){
    margin-bottom: 0;
  }
}

</style>